#!/usr/bin/env python3
"""
固定资产管理系统部署脚本
支持开发环境和生产环境的自动化部署
"""

import os
import sys
import subprocess
import argparse
from pathlib import Path


class AssetManagementDeployer:
    def __init__(self, environment='development'):
        self.environment = environment
        self.project_root = Path(__file__).parent
        self.requirements_file = self.project_root / 'requirements.txt'
        
    def run_command(self, command, check=True):
        """执行命令"""
        print(f"执行命令: {command}")
        try:
            result = subprocess.run(
                command, 
                shell=True, 
                check=check,
                capture_output=True,
                text=True
            )
            if result.stdout:
                print(result.stdout)
            return result
        except subprocess.CalledProcessError as e:
            print(f"命令执行失败: {e}")
            if e.stderr:
                print(f"错误信息: {e.stderr}")
            if check:
                sys.exit(1)
            return e
    
    def check_python_version(self):
        """检查Python版本"""
        print("检查Python版本...")
        version = sys.version_info
        if version.major < 3 or (version.major == 3 and version.minor < 8):
            print("错误: 需要Python 3.8或更高版本")
            sys.exit(1)
        print(f"✓ Python版本: {version.major}.{version.minor}.{version.micro}")
    
    def create_virtual_environment(self):
        """创建虚拟环境"""
        venv_path = self.project_root / '.venv'
        if venv_path.exists():
            print("✓ 虚拟环境已存在")
            return
        
        print("创建虚拟环境...")
        self.run_command(f"python -m venv {venv_path}")
        print("✓ 虚拟环境创建完成")
    
    def install_dependencies(self):
        """安装依赖包"""
        print("安装依赖包...")
        
        # 创建requirements.txt如果不存在
        if not self.requirements_file.exists():
            self.create_requirements_file()
        
        # 根据操作系统选择激活命令
        if os.name == 'nt':  # Windows
            activate_cmd = '.venv\\Scripts\\activate'
            pip_cmd = '.venv\\Scripts\\pip'
        else:  # Unix/Linux/macOS
            activate_cmd = 'source .venv/bin/activate'
            pip_cmd = '.venv/bin/pip'
        
        # 升级pip
        self.run_command(f"{pip_cmd} install --upgrade pip")
        
        # 安装依赖
        self.run_command(f"{pip_cmd} install -r {self.requirements_file}")
        print("✓ 依赖包安装完成")
    
    def create_requirements_file(self):
        """创建requirements.txt文件"""
        requirements = [
            "Django>=4.2.0,<5.0",
            "Pillow>=9.0.0",
            "openpyxl>=3.0.0",
            "qrcode[pil]>=7.0.0",
            "reportlab>=3.6.0",
            "psutil>=5.8.0",
            "python-dateutil>=2.8.0",
            "django-extensions>=3.2.0",
            "django-debug-toolbar>=4.0.0",
            "whitenoise>=6.0.0",
            "gunicorn>=20.1.0",
        ]
        
        with open(self.requirements_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(requirements))
        
        print(f"✓ 创建requirements.txt文件: {self.requirements_file}")
    
    def setup_database(self):
        """设置数据库"""
        print("设置数据库...")
        
        # 执行迁移
        self.run_command("python manage.py makemigrations")
        self.run_command("python manage.py migrate")
        
        # 初始化系统参数
        self.run_command("python manage.py init_system_params")
        
        print("✓ 数据库设置完成")
    
    def create_superuser(self):
        """创建超级用户"""
        print("创建超级用户...")
        
        # 检查是否已存在超级用户
        result = self.run_command(
            "python manage.py shell -c \"from django.contrib.auth.models import User; print(User.objects.filter(is_superuser=True).exists())\"",
            check=False
        )
        
        if "True" in result.stdout:
            print("✓ 超级用户已存在")
            return
        
        print("请创建超级用户账户:")
        self.run_command("python manage.py createsuperuser")
        print("✓ 超级用户创建完成")
    
    def collect_static_files(self):
        """收集静态文件"""
        if self.environment == 'production':
            print("收集静态文件...")
            self.run_command("python manage.py collectstatic --noinput")
            print("✓ 静态文件收集完成")
    
    def create_media_directories(self):
        """创建媒体文件目录"""
        print("创建媒体文件目录...")
        
        media_dirs = [
            'media/assets/images',
            'media/assets/qrcodes',
            'media/backups',
            'static/images',
        ]
        
        for dir_path in media_dirs:
            full_path = self.project_root / dir_path
            full_path.mkdir(parents=True, exist_ok=True)
            print(f"✓ 创建目录: {full_path}")
    
    def create_default_icons(self):
        """创建默认图标文件"""
        print("创建默认PWA图标...")
        
        # 这里可以创建默认的图标文件
        # 为了简化，我们创建占位符文件
        icon_sizes = [72, 96, 128, 144, 152, 192, 384, 512]
        
        for size in icon_sizes:
            icon_path = self.project_root / f'static/images/icon-{size}x{size}.png'
            if not icon_path.exists():
                # 创建一个简单的占位符文件
                icon_path.touch()
                print(f"✓ 创建图标占位符: {icon_path}")
    
    def setup_environment_file(self):
        """设置环境变量文件"""
        env_file = self.project_root / '.env'
        
        if env_file.exists():
            print("✓ .env文件已存在")
            return
        
        print("创建环境变量文件...")
        
        env_content = f"""# 固定资产管理系统环境配置
DEBUG={'True' if self.environment == 'development' else 'False'}
SECRET_KEY=your-secret-key-here-change-in-production
ALLOWED_HOSTS=localhost,127.0.0.1

# 数据库配置
DATABASE_URL=sqlite:///db.sqlite3

# 媒体文件配置
MEDIA_ROOT=media/
STATIC_ROOT=staticfiles/

# 邮件配置
EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend
EMAIL_HOST=
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=
EMAIL_HOST_PASSWORD=

# 缓存配置
CACHE_BACKEND=django.core.cache.backends.locmem.LocMemCache

# 日志配置
LOG_LEVEL={'DEBUG' if self.environment == 'development' else 'INFO'}
"""
        
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write(env_content)
        
        print(f"✓ 创建环境变量文件: {env_file}")
        print("⚠ 请根据实际情况修改.env文件中的配置")
    
    def run_tests(self):
        """运行测试"""
        if self.environment == 'development':
            print("运行测试...")
            result = self.run_command("python manage.py test", check=False)
            if result.returncode == 0:
                print("✓ 所有测试通过")
            else:
                print("⚠ 部分测试失败，请检查")
    
    def generate_demo_data(self):
        """生成演示数据"""
        if self.environment == 'development':
            print("生成演示数据...")
            self.run_command("python manage.py generate_ai_demo_data --count 10")
            print("✓ 演示数据生成完成")
    
    def health_check(self):
        """系统健康检查"""
        print("执行系统健康检查...")
        self.run_command("python manage.py system_health_check")
        print("✓ 系统健康检查完成")
    
    def deploy(self):
        """执行完整部署"""
        print("=" * 60)
        print(f"开始部署固定资产管理系统 ({self.environment}环境)")
        print("=" * 60)
        
        try:
            # 1. 检查Python版本
            self.check_python_version()
            
            # 2. 创建虚拟环境
            self.create_virtual_environment()
            
            # 3. 安装依赖
            self.install_dependencies()
            
            # 4. 创建必要目录
            self.create_media_directories()
            
            # 5. 创建默认图标
            self.create_default_icons()
            
            # 6. 设置环境变量
            self.setup_environment_file()
            
            # 7. 设置数据库
            self.setup_database()
            
            # 8. 创建超级用户
            self.create_superuser()
            
            # 9. 收集静态文件
            self.collect_static_files()
            
            # 10. 生成演示数据
            self.generate_demo_data()
            
            # 11. 运行测试
            self.run_tests()
            
            # 12. 健康检查
            self.health_check()
            
            print("=" * 60)
            print("🎉 部署完成！")
            print("=" * 60)
            
            if self.environment == 'development':
                print("开发环境启动命令:")
                print("python manage.py runserver")
                print("\n访问地址:")
                print("http://127.0.0.1:8000/")
            else:
                print("生产环境启动命令:")
                print("gunicorn asset_management.wsgi:application --bind 0.0.0.0:8000")
            
            print("\n管理后台:")
            print("http://127.0.0.1:8000/admin/")
            
        except Exception as e:
            print(f"❌ 部署失败: {e}")
            sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description='固定资产管理系统部署脚本')
    parser.add_argument(
        '--env',
        choices=['development', 'production'],
        default='development',
        help='部署环境 (默认: development)'
    )
    parser.add_argument(
        '--skip-tests',
        action='store_true',
        help='跳过测试'
    )
    
    args = parser.parse_args()
    
    deployer = AssetManagementDeployer(args.env)
    deployer.deploy()


if __name__ == '__main__':
    main()